/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dailydev.wave.robot.servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dailydev.wave.robot.IRobot;
import org.dailydev.wave.robot.RobotException;
import org.dailydev.wave.robot.serializer.CapabilitiesSerializer;
import org.dailydev.wave.robot.serializer.ISerializer;

/**
 * @author Roman Bosak, DailyDev.org
 */
public class CapabilitiesServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = -2145522801768623854L;

    /**
     * Logger for request and response payload
     */
    private static Logger payloadLog = Logger.getLogger("robot.payload.events");

    protected IRobot robot;

    protected ISerializer<IRobot> capabilitiesGenerator = new CapabilitiesSerializer();

    private String capabilitiesDocument;

    /** {@inheritDoc} */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (capabilitiesDocument == null) {
            try {
                capabilitiesDocument = capabilitiesGenerator.serialize(robot);
            } catch (RobotException e) {
                throw new ServletException("Capabilities document generation failed.", e);
            }
        }

        resp.setContentType("text/xml");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(capabilitiesDocument);
        resp.setStatus(200);

        if (payloadLog.isLoggable(Level.FINEST)) {
            payloadLog.finest("RESPONSE: 200 OK : " + capabilitiesDocument);
        }
    }

    /** {@inheritDoc} */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        String robotFactoryClassName = config.getServletContext().getInitParameter(
                IRobotFactory.ROBOT_FACTORY__PARAM_NAME);
        try {
            Class<IRobotFactory> robotFactoryClass = (Class<IRobotFactory>) Class.forName(robotFactoryClassName);
            IRobotFactory robotFactory = robotFactoryClass.newInstance();
            robot = robotFactory.buildRobot(config);
        } catch (ClassNotFoundException e) {
            throw new ServletException("Unable to find robot factory class '" + robotFactoryClassName + "'", e);
        } catch (InstantiationException e) {
            throw new ServletException("Unable to instantiate robot factory class '" + robotFactoryClassName + "'", e);
        } catch (IllegalAccessException e) {
            throw new ServletException("Unable to instantiate robot factory class '" + robotFactoryClassName + "'", e);
        }
    }

}
